package com.pub.tools;

import java.sql.*;
import java.text.*;
import java.util.*;
import java.util.Date;

import com.pub.check.*;

public class PublicFunction {
    private static boolean blnDebug = false;
    public PublicFunction() {
    }

    /*目的：replace 字串(同上一個method)但對要替代的字串忽略大小寫做比較
      傳入：原來的字串，欲替代的字串,被替代後的字串,是否忽略大小寫做比較
      傳回：replace後的字串
      範例：String strSql = PublicCheck.replace("Insert info Table1 values(ABc)","ab","c",true);
      結果：strSql = "Insert into Table1 values('cc')"
     */
    public static String replace(String pstrSource, String pstrFind,
                                 String pstrReplace, boolean pblnIgnoreCase) {
        StringBuffer lstbRtn = new StringBuffer();
        boolean lblnCompareResult = false;

        try {
            if (pstrSource != null && (!pstrSource.trim().equals(""))) {
                for (int i = 0; i < pstrSource.length(); i++) {
                    if ((i + pstrFind.length()) <= pstrSource.length()) {
                        if (!pblnIgnoreCase) { //要比較大小寫
                            lblnCompareResult = pstrSource.substring(i,
                                    i + pstrFind.length()).equals(pstrFind);
                        } else {
                            lblnCompareResult = pstrSource.substring(i,
                                    i +
                                    pstrFind.length()).equalsIgnoreCase(
                                            pstrFind);
                        }
                        if (lblnCompareResult) {
                            lstbRtn.append(pstrReplace);
                            i = i + (pstrFind.length() - 1);
                        } else {
                            lstbRtn.append(pstrSource.substring(i, i + 1));
                        }
                    } else {
                        lstbRtn.append(pstrSource.substring(i, i + 1));
                    }
                } //end-for
            } else {
                lstbRtn.append("");
            }
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:replace --> Exception=" + ex.toString());
        }
        return lstbRtn.toString();
    }

    /*目的：取出系統日期 (overload)
      傳入：無
      傳回：日期字串 ("2003/12/25")
      範例：String strSYSDATE = PublicCheck.getSYSDATE();
     */
    public static String getSYSDATE() {
        String strDate = "";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            Date dteNOW = new Date();
            strDate = formatter.format(dteNOW).toString();
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:getSYSDATE()  --> Exception=" +
                               ex.toString());
        }
        return strDate;
    } //getSYSDATE

    /*目的：取出系統日期 (overload)，此方法要特別留意傳入的格式字串必須正確
      傳入：格式字串 ex:"yyyy/MM/dd HH/mm/ss"
      傳回：日期字串 ex:"2003/12/25 16:11:02"
      範例：String strSYSDATE = PublicCheck.getSYSDATE("yyyy/MM/dd HH:mm:ss");
     */
    public static String getSYSDATE(String strFormat) {
        String strDate = "";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(strFormat.
                    toString());
            Date dteNOW = new Date();
            strDate = formatter.format(dteNOW).toString();
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:getSYSDATE(String strFormat)  --> Exception=" +
                               ex.toString());
        }
        return strDate;
    } //getSYSDATE

    /*目的：取出系統日期 (overload)，此方法要特別留意傳入的格式字串必須正確
      用意：必須要針對目前的日期或時間做一些加減動作時，才比較需要用到
      傳入：日期物件 ex:Date()==>用DateFormat.getDateInstance().parse將字串"92/12/01"轉成Date物件 ,格式字串 ex:"yyyy/MM/dd HH/mm/ss"
      傳回：日期字串 ("2003/12/25 16:11:02")
      範例：import java.text.*;
           String strSYSDATE = PublicCheck.getSYSDATE(DateFormat.getDateInstance().parse("2004/01/01"),"yyyy/MM/dd HH/mm/ss");  */
    public static String getSYSDATE(Date dteTemp, String strFormat) {
        String strDate = "";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(strFormat);
            strDate = formatter.format(dteTemp).toString();
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:getSYSDATE(Date dteTemp,String strFormat) --> Exception=" +
                               ex.toString());
        }
        return strDate;
    } //getSYSDATE

    /*目的：取出日期物件的字串 (overload)，此方法要特別留意傳入的格式字串必須正確
     傳入：日期物件 Date() ==>用DateFormat.getDateInstance().parse將字串"92/12/01"轉成Date物件
      傳回：日期字串 ("2003/12/25"),固定格式"yyyy/MM/dd"
      範例：import java.text.*;
           String strSYSDATE = PublicCheck.getSYSDATE(DateFormat.getDateInstance().parse((arlDataItem.get(3).toString().substring(0,arlDataItem.get(3).toString().indexOf("."))).replace('-','/')));  */
    public static String getSYSDATE(Date dteTemp) {
        String strDate = "";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            strDate = formatter.format(dteTemp).toString();
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:getSYSDATE(Date dteTemp) --> Exception=" +
                               ex.toString());
        }
        return strDate;
    } //getSYSDATE

    /*目的：取出系統日期增加年、月、日(overload)，此方法要特別留意傳入的格式字串必須正確
      傳入：strType  => "Y" 年,"M" 月,"D" 日
           intValue => 增加或減少的變量
           strFormat=> ex:"yyyy/MM/dd"
      傳回：日期字串 ex:"2005/08/12"
     範例：String strSYSDATE = PublicCheck.getSYSDATE("Y",1,"yyyy/MM/dd"); //年度+1 */
    public static String getSYSDATE(String strType, int intValue,
                                    String strFormat) {
        String strDate = "";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(strFormat);
            Calendar cld = Calendar.getInstance();
            if (strType.trim().equalsIgnoreCase("Y")) {
                cld.set(Calendar.YEAR,
                        Calendar.getInstance().get(Calendar.YEAR) + intValue);
            }
            if (strType.trim().equalsIgnoreCase("M")) {
                cld.set(Calendar.MONTH,
                        Calendar.getInstance().get(Calendar.MONTH) + intValue);
            }
            if (strType.trim().equalsIgnoreCase("D")) {
                cld.set(Calendar.DATE,
                        Calendar.getInstance().get(Calendar.DATE) + intValue);
            }
            strDate = formatter.format(cld.getTime());
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:getSYSDATE(String strType,int intValue) --> Exception=" +
                               ex.toString());
        }
        return strDate;
    }

    /**
     * getSYSDATE
     *
     * @param pstrDate String
     * @param pstrFormat String
     * @return String
     */
    public static String getSYSDATE(String pstrDate, String pstrFormat) {
        String lstrDate = null;
        try {
            lstrDate = PublicFunction.getSYSDATE(DateFormat.getDateInstance().parse(
                    pstrDate.replaceAll("-", "/")), pstrFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lstrDate;
    }

    public static Timestamp getTimestempDate(String strDesDate) {
        try {
            //because:Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
            if (strDesDate == null || strDesDate.trim().equals("")) {
                return null;
            } else {
                if(strDesDate.indexOf(":")<0){
                    strDesDate=(new StringBuffer(strDesDate)).append(" 00:00:00").toString();
                }
                else if(strDesDate.indexOf(":",strDesDate.indexOf(":")+1)<0){
                    strDesDate=(new StringBuffer(strDesDate)).append(":00").toString();
                }
                return Timestamp.valueOf(strDesDate.replaceAll("/","-"));
            }
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:getTimestempDate --> Exception=" +
                               ex.toString());
            return null;
        }
    }


    public static String[] split(String strSource, String strCut) {
        ArrayList<String> arlData = new ArrayList<String>();
        String strTemp = "";
        int l = 1; //字串陣列的大小
        try {
            if (blnDebug) {
                System.out.println("\nPublicCheck.java" + " (split) --> Start ");
            }
            if (blnDebug) {
                System.out.println("傳入值=" + strSource);
            }
            if (blnDebug) {
                System.out.println("分隔符號=" + strCut);
            }
            if (strSource != null && (!strSource.trim().equals("")) && strCut != null &&
                (!strCut.trim().equals(""))) { //代表傳入的字串有值
                if (strSource.indexOf(strCut) != -1) { //代表字串中有此字元
                    strTemp = strSource;
                    //if (blnDebug) System.out.println("strTemp.indexOf(strCut) = "+strTemp.indexOf(strCut));
                    while (strTemp.indexOf(strCut) != -1) {
                        //if (blnDebug) System.out.println(l + ". " + strTemp.substring(0,strTemp.indexOf(strCut)));
                        arlData.add(strTemp.substring(0, strTemp.indexOf(strCut)));
                        strTemp = strTemp.substring(strTemp.indexOf(strCut) +
                                strCut.length());
                        //if (blnDebug) System.out.println(l + ". " + strTemp);
                        l++;
                    }
                    arlData.add(strTemp);
                } else { //代表字串中沒有此字元
                    l = 1;
                }
            } else {
                l = 1; //代表只有一個
            }
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:split --> Exception=" + ex.toString());
        }

        String svParam[];
        svParam = new String[l];
        try {
            if (l == 1) {
                svParam[0] = strSource;
                if (blnDebug) {
                    System.out.println("回傳值[0]=" + svParam[0]);
                }
            } else {
                for (int i = 0; i < arlData.size(); i++) {
                    svParam[i] = arlData.get(i).toString();
                    if (blnDebug) {
                        System.out.println("回傳值[" + i + "]=" + svParam[i]);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:split --> Exception=" + ex.toString());
        } finally {
            arlData = null;
            if (blnDebug) {
                System.out.println("PublicCheck.java" + " (split) --> End ");
            }
            
        }
        return svParam;
    } //split

    /*--------------------------------------------------------------
      目的   : 用來擷取一段字串中，以分隔符號切開後所指定要回傳第幾組的值
      輸入參數: pstrSource -- 含分隔符號的字串
               pstrRegex  -- 分隔符號
               pintIndex  -- 要回傳第幾組字串
      傳回值  : Ex.getDesSplitString("123,456,789",",",1) return "456"
     -------------------------------------------------------------- */
    public static String getDesSplitString(String pstrSource, String pstrRegex,
                                           int pintIndex) {
        String lstrRtn = "";
        String lstrSplit[] = null;
        try {
            //JDK 1.3 版本後有提供split method可直接切開字串，會使用JDK提供方法主因是PublicCheck.split當字串很長
            //時，會有performance問題
            if (Float.parseFloat(System.getProperty(
                    "java.specification.version")) >= 1.3) {
                lstrSplit = pstrSource.split(pstrRegex);
            } else {
                lstrSplit = PublicFunction.split(pstrSource, pstrRegex);
            }

            lstrRtn = (pintIndex <= lstrSplit.length - 1 ?
                       new String(lstrSplit[pintIndex]) : "");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lstrSplit = null;
            
        }
        return lstrRtn;
    }

    /**
     * 計算字串中含有幾個特定字串
     *
     * @param pstrSource String 欲計算的字串
     * @param pstrDesStr String 特定字串
     * @return int
     * @sample getDesStrCount("abcdabcefsc","c")=3
     */
    public static int getDesStrCount(String pstrSource, String pstrDesStr) {
        int lintCount = 0;
        try {
            for (int i = 0; i <= pstrSource.length() - 1; i++) {
                if (pstrSource.indexOf(pstrDesStr, i) != -1) {
                    lintCount++;
                    i = pstrSource.indexOf(pstrDesStr,i) + pstrDesStr.length();
                }
            }
            return lintCount;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 將html form內input text value從來源碼(strSourceCode)轉成目的編碼(strTargetCode)
     * ex:getTransCode(parameter,"8859_1","UTF-8")
     * @param parameter - input text value
     * @return target encoding value
     */
    public static String getTransCode(String parameter, String strSourceCode,
                                      String strTargetCode) {
        try {
            return new String(parameter.getBytes(strSourceCode), strTargetCode);
        } catch (Exception ex) {
            return "";
        }
    }

    /*
         目的：轉換日期字串變成Integer型態
         傳入：日期字串 ("92/12/24")
         傳回：int 日期 (921224)
         範例：int intSYSDATE = DateToInt(DateFormat.getDateInstance().format(new Date()).toString());
         若系統日期 = "92/12/24" 則回傳 921224
     */
    public static int DateToInt(String strDate) {
        int intDate = 0;

        if (strDate != null) {
            if (!strDate.equals("")) {
                int i = strDate.indexOf("/");
                int j = strDate.lastIndexOf("/");
                int yy = Integer.parseInt(strDate.substring(0, i));
                int mm = Integer.parseInt(strDate.substring(i + 1, j));
                int dd = Integer.parseInt(strDate.substring(j + 1));
                intDate = yy * 10000 + mm * 100 + dd;
            }
        }
        return intDate;
    } //DateToInt

    /**
     * 傳回固定位數的空白
     */
    public static String spaces(int len) {
        StringBuffer str = new StringBuffer("");
        for (int i = 0; i < len; i++) {
            str.append(" ");
        }
        return str.toString();
    } //End of spaces

    /* 將字串轉成整數,用來改善 Integer.parseInt() 的一些不便利之處
       主要作用為
       1. 避開 null Exception, 如果傳入 null 則傳回 0
       2. 避開 NumberFormatException, 如果無法轉換成 int 的字串則傳回 0
       3. 避開開頭第一個字元是 + 所造成的錯誤
       4. 避開浮點數所造成的 Exception, 如果是浮點數則採取無條件去尾法,例如 89.83 就轉成 89
     */
    public static int String_to_int(String num) {
        int a = 0;
        if (!PublicCheck.isNumString(num)) {
            return 0;
        }
        if (PublicCheck.isIntString(num)) {
            if (num.startsWith("+")) {
                num = num.substring(1);
            }
            try {
                a = Integer.parseInt(num);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            a = (int) Float.parseFloat(num);
        }
        return a;
    } //String_to_int

    /**
     * 取得物件的Java 程式名稱
     * @param pobjInstance Object 實體物件
     * @return String 程式名稱(ex.PublicCheck.java)
     */
    public static String getObjectName(Object pobjInstance) {
        if (pobjInstance instanceof Object) {
            return pobjInstance.toString().substring(pobjInstance.toString().
                    lastIndexOf('.') +
                    1,
                    pobjInstance.toString().
                    lastIndexOf('@')) +
                    ".java";

        } else {
            return "not instance object";
        }
    }

    /**
     * 取得字串中雙位元組字元的unicode
     *
     * @param pstrContent String
     * @return String
     * @throws Exception
     */
    public static String getDoubleBytesStrUnicode(String pstrContent) throws Exception {
        StringBuffer lstbUnicode = new StringBuffer();
        for (int i = 0; i < pstrContent.length(); i++) {
            if(String.valueOf(pstrContent.charAt(i)).getBytes().length==2){
                lstbUnicode.append("\\u");
                lstbUnicode.append(Integer.toHexString((int) pstrContent.charAt(
                        i)));
            }
            else{
                lstbUnicode.append(pstrContent.charAt(i));
            }
        }
        return lstbUnicode.toString();
    }
}
